package cc.telecomdigital.tdstock.trading;

import java.util.List;

import com.lightstreamer.ls_client.UpdateInfo;

import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.Application_Framework.LS_ItemRequestType;
import cc.telecomdigital.tdstock.Framework.UniqueItem.DeviceInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Services.LS_SubscriptionItem;
import cc.telecomdigital.tdstock.Services.LS_UserClient.CONNECTION_STATUS;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Response;

import cc.telecomdigital.tdstock.trading.Common.Trade_AppConstant;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockHistItem;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockReqOrderItem;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockViewInfoItem;
import cc.telecomdigital.tdstock.trading.Common.Trade_SymbolTranslation;
import cc.telecomdigital.tdstock.trading.Services.TradeAppInfo;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote;
import cc.telecomdigital.tdstock.trading.Services.TradeOrderCancel;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.ITradeGetStockQuoteResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.TradeGetStockQuoteResult;
import cc.telecomdigital.tdstock.trading.Services.TradeOrderCancel.ITradeOrderCancelResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeOrderCancel.TradeOrderCancelResult;
import cc.telecomdigital.tdstock.trading.Tools.Trade_StockFunctionTools;
import cc.telecomdigital.tdstock.trading.widget.AppDialogOK;
import cc.telecomdigital.tdstock.trading.widget.AppDialogOKCancel;
import cc.telecomdigital.tdstock.trading.widget.AppDialogPassword;
import cc.telecomdigital.tdstock.trading.widget.SwipeView;
import cc.telecomdigital.tdstock.trading.widget.SwipeView.OnPageChangedListener;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.TextView;

//Data are passed in by parcel with the intent filled
public class Trade_AcctOrderDetailActivity extends Trade_TemplateActivity
	implements Button.OnClickListener, ILS_UserClient_Response, OnPageChangedListener
{
	private int							focusIndex = 0;
	private List<Trade_StockHistItem>		     transInfoList;
	private String systemLang;
	private SwipeView swipFlipper;
	
	@Override
	public void onCreate(Bundle iSaveInstance)
	{
		ImageButton imgButtonObj;
		Button buttonObj;
		TextView textViewObj;

		super.onCreate(iSaveInstance);
		setContentView(R.layout.stockorder_detail);
		systemLang = DeviceInfo.GetLanguageString();
		
		imgButtonObj = (ImageButton) findViewById(R.id.stockorder_details_BackBut);
		imgButtonObj.setOnClickListener(this);

		textViewObj = (TextView) findViewById(R.id.stockorder_details_Title);
		if (TradeAppInfo.IsDemoAccount())
			textViewObj.setText(TradeAppInfo.GetUserName());
		else
			textViewObj.setText(R.string.transHistoryText);

		// Set the Width for the bottom direction all data
		buttonObj = (Button) findViewById(R.id.view_stockorder_detail_EditBut);
		buttonObj.setWidth(fScrWidthPixel / 2);
		buttonObj.setOnClickListener(this);

		buttonObj = (Button) findViewById(R.id.view_stockorder_detail_CancelBut);
		buttonObj.setWidth(fScrWidthPixel / 2);
		buttonObj.setOnClickListener(this);

		imgButtonObj = (ImageButton) findViewById(R.id.view_stockorder_detail_PagePrevBut);
		imgButtonObj.setOnClickListener(this);

		imgButtonObj = (ImageButton) findViewById(R.id.view_stockorder_detail_PageNextBut);
		imgButtonObj.setOnClickListener(this);

		Intent rcvIntent;
		Bundle bundlePackage;

		rcvIntent = getIntent();
		//Initialize a dummy protection
		focusIndex    = 0;
		transInfoList = null;
		
		if (rcvIntent != null)
		{
			bundlePackage = rcvIntent.getExtras();
			if (bundlePackage != null)
			{
				focusIndex = bundlePackage.getInt( Trade_AppConstant.stockOrderFilterListIndex,
										 	focusIndex);
				transInfoList = bundlePackage.getParcelableArrayList(Trade_AppConstant.stockOrderFilterList);
			}				
		}

		swipFlipper = (SwipeView)findViewById(R.id.view_stockorder_detail_swipeView);
		
		int index, count;
		View tmpObj;
		String       statusCode;

		if (transInfoList != null)
		{
			count = transInfoList.size();
			//Just create the layout to buy some time first
			for (index = 0; index < count; index++)		
				swipFlipper.addView(new FrameLayout(actContext));	
		
			// Create three pages maximum for movement
		
			//Create the previous page if possible
			index = focusIndex-1;
			if (index >= 0)
			{
				tmpObj = CreateContentView(transInfoList.get(index));		
				((FrameLayout) swipFlipper.getChildContainer().getChildAt(index)).addView(tmpObj);			
			}
		
			index = focusIndex;
			tmpObj = CreateContentView(transInfoList.get(index));		
			((FrameLayout) swipFlipper.getChildContainer().getChildAt(index)).addView(tmpObj);
		
			//Create the next page if possible
			index = focusIndex+1;
			if (index < count)
			{
				tmpObj = CreateContentView(transInfoList.get(index));		
				((FrameLayout) swipFlipper.getChildContainer().getChildAt(index)).addView(tmpObj);				
			}
			
			//Set for the first page
			swipFlipper.scrollToPage(focusIndex);
			statusCode = transInfoList.get(focusIndex).statusCode;
			UpdatePageInfo(focusIndex, Trade_SymbolTranslation.IsStockOrderEditable(statusCode));
			
			//Set onpAge Listener at last after finishing
			swipFlipper.setOnPageChangedListener(this);
		}			
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
		LightStreamerTimeoutTaskCancel();
	}	
	
	/** Update the display info with the current list on hand **/
	private View CreateContentView(Trade_StockHistItem iTradeItem)
	{
		TextView textViewObj;
		String tmpString, convertString;
		Resources contRes;
		String processStatus;
		String curSign;
		int    curTextColor;
		int    redColor, blueColor, whiteColor, dimYellowColor, greenColor;
		View   viewObj;
		
		LayoutInflater inflatObj = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		viewObj = inflatObj.inflate(R.layout.view_stockorder_detail_content, null);		
		
		contRes = getResources();
		
		redColor  = contRes.getColor(R.color.Red);
		blueColor = contRes.getColor(R.color.Blue);
		whiteColor = contRes.getColor(R.color.White);
		dimYellowColor = contRes.getColor(R.color.DimYellow);
		greenColor    = contRes.getColor(R.color.Green);
		
		textViewObj = (TextView) viewObj.findViewById(R.id.view_stockorder_detail_Name);
		tmpString = iTradeItem.stockCode;
		if (systemLang.equals("lang_cht"))
			tmpString += " " + iTradeItem.chnName;
		else
			tmpString += " " + iTradeItem.engName;
		textViewObj.setText(tmpString);

		processStatus = iTradeItem.statusCode;
		textViewObj = (TextView) viewObj.findViewById(R.id.view_stockorder_detail_Status);

		// Set Color for the text
		if (processStatus.equals("2"))
			textViewObj.setTextColor(greenColor);
		else if (processStatus.equals("4") || processStatus.equals("3"))
			textViewObj.setTextColor(redColor);
		else
			textViewObj.setTextColor(whiteColor);
		textViewObj.setText(iTradeItem.statusName);

		textViewObj = (TextView) viewObj.findViewById(R.id.view_stockorder_detail_Time);
		textViewObj.setText(iTradeItem.orderTime);

		textViewObj = (TextView) viewObj.findViewById(R.id.view_stockorder_detail_OrderNo);
		textViewObj.setText(iTradeItem.orderNo);

		textViewObj = (TextView) viewObj.findViewById(R.id.view_stockorder_detail_Media);
		textViewObj.setText(iTradeItem.channel);

		// Buy or sell
		textViewObj = (TextView)viewObj.findViewById(R.id.view_stockorder_detail_TransType);

		//New		
		if (iTradeItem.orderSide.equals(Trade_SymbolTranslation.TRANSACTIONTYPE_BID))
			textViewObj.setBackgroundColor(blueColor);
		else if (iTradeItem.orderSide
				.equals(Trade_SymbolTranslation.TRANSACTIONTYPE_ASK))
		textViewObj.setBackgroundColor(redColor);			

		// Order Side comes with B and A, and OrderType is the E, market
		// and etc...
		tmpString = Trade_SymbolTranslation.TranslateTransType(this, iTradeItem.orderSide);
		textViewObj.setText(tmpString);

		textViewObj = (TextView) viewObj.findViewById(R.id.view_stockorder_detail_TransPrice);
		convertString = Trade_StockFunctionTools.AutoFillInDecimal(iTradeItem.price,
											Trade_AppConstant.priceValueStringWithDec);
		if (iTradeItem.currencyCode.equals(TradeAppInfo.CNYCode))
		{
			textViewObj.setTextColor(dimYellowColor);
			curSign = TradeAppInfo.CNYSign;
			curTextColor = dimYellowColor;
		}				
		else if (iTradeItem.currencyCode.equals(TradeAppInfo.USDCode))
		{					
			textViewObj.setTextColor(dimYellowColor);
			curSign = TradeAppInfo.USDSign;
			curTextColor = dimYellowColor;				
		}				
		else
		{				
			textViewObj.setTextColor(whiteColor);
			curSign = TradeAppInfo.HKDSign;
			curTextColor = whiteColor;				
		}
		
		convertString = curSign + Trade_StockFunctionTools.AddFormatToThousand(convertString);
		textViewObj.setText(convertString);
			
		if (iTradeItem.orderSide.equals(Trade_SymbolTranslation.TRANSACTIONTYPE_BID))
			textViewObj.setBackgroundColor(contRes.getColor(R.color.Blue));
		else if (iTradeItem.orderSide
				.equals(Trade_SymbolTranslation.TRANSACTIONTYPE_ASK))
			textViewObj.setBackgroundColor(contRes.getColor(R.color.Red));				
			
		//Original Order
		textViewObj = (TextView)viewObj.findViewById(R.id.view_stockorder_detail_TotalVol);
		convertString = Trade_StockFunctionTools.AddFormatToThousand(iTradeItem.quantity);
		textViewObj.setText(convertString);
		
		textViewObj = (TextView)viewObj.findViewById(R.id.view_stockorder_detail_TotalPrice);
		convertString = Trade_StockFunctionTools.CalculateProductInPrice(iTradeItem.quantity, 
															iTradeItem.price);
		
		//Modify with fill in decimal
		convertString = Trade_StockFunctionTools.AutoFormatPriceToCents(convertString);
		
		convertString = curSign + Trade_StockFunctionTools.AddFormatToThousand(convertString);			
		textViewObj.setText(convertString);
		textViewObj.setTextColor(curTextColor);

		//Filled Order
		textViewObj = (TextView)viewObj.findViewById(R.id.view_stockorder_detail_PerformedVol);
		convertString = Trade_StockFunctionTools.AddFormatToThousand(iTradeItem.fillQuantity);
		textViewObj.setText(convertString);
		if (iTradeItem.fillQuantity.equals("0") == false)
			textViewObj.setTextColor(greenColor);
		else
			textViewObj.setTextColor(whiteColor);			
	
		textViewObj = (TextView)viewObj.findViewById(R.id.view_stockorder_detail_PerformedPrice);
		convertString = Trade_StockFunctionTools.CalculateProductInPrice(iTradeItem.fillQuantity, 
				iTradeItem.price);
		
		//Modify with fill in decimal
		convertString = Trade_StockFunctionTools.AutoFormatPriceToCents(convertString);		
		
		convertString = curSign + Trade_StockFunctionTools.AddFormatToThousand(convertString);			
		textViewObj.setText(convertString);
		textViewObj.setTextColor(curTextColor);			
				
		//Cancel Order
		textViewObj = (TextView)viewObj.findViewById(R.id.view_stockorder_detail_RemainingVol);
		convertString = Trade_StockFunctionTools.AddFormatToThousand(iTradeItem.outstandQuantity);
		textViewObj.setText(convertString);

		textViewObj = (TextView)viewObj.findViewById(R.id.view_stockorder_detail_RemainingPrice);
		convertString = Trade_StockFunctionTools.CalculateProductInPrice(iTradeItem.outstandQuantity, 
															iTradeItem.price);
		
		//Modify with fill in decimal
		convertString = Trade_StockFunctionTools.AutoFormatPriceToCents(convertString);
		
		convertString = curSign + Trade_StockFunctionTools.AddFormatToThousand(convertString);			
		textViewObj.setText(convertString);
		textViewObj.setTextColor(curTextColor);				
			
		if ((iTradeItem.details != null) && (iTradeItem.details.size() != 0))
		{
			int count, index;

			viewObj.findViewById(R.id.view_stockorder_detail_ExtraInfoPanel)
					.setVisibility(View.VISIBLE);
			textViewObj = (TextView)viewObj.findViewById(R.id.view_stockorder_detail_ExtraInfo);
			count = iTradeItem.details.size();
			tmpString = "";
			for (index = 0; index < count; index++)
				tmpString += iTradeItem.details.get(index) + "\n";

			textViewObj.setText(tmpString);
		}
		else
			viewObj.findViewById(R.id.view_stockorder_detail_ExtraInfoPanel)
					.setVisibility(View.GONE);
	
		return viewObj;
	}
		
	/** Update the focused page Info on the display, such as 1/20 or 2/10 **/
	private void UpdatePageInfo(int iIndex, boolean iEditable)
	{
		int index, count;
		String tmpString;
		Button actionButton;
		TextView textViewObj;

		index = iIndex + 1;
		count = -1;
		if (transInfoList != null)
			count = transInfoList.size();
		else
			index = -1;

		// PageInfo and edit-able or not
		textViewObj = (TextView) findViewById(R.id.view_stockorder_detail_PageInfo);
		tmpString = Integer.toString(index) + "/" + Integer.toString(count);
		textViewObj.setText(tmpString);

		actionButton = (Button) findViewById(R.id.view_stockorder_detail_EditBut);
		actionButton.setEnabled(iEditable);

		actionButton = (Button) findViewById(R.id.view_stockorder_detail_CancelBut);
		actionButton.setEnabled(iEditable);

		if ((index == 1) || (index == -1))
			findViewById(R.id.view_stockorder_detail_PagePrevBut)
					.setVisibility(View.INVISIBLE);
		else
			findViewById(R.id.view_stockorder_detail_PagePrevBut)
					.setVisibility(View.VISIBLE);

		if ((index == count) || (index == -1))
			findViewById(R.id.view_stockorder_detail_PageNextBut)
					.setVisibility(View.INVISIBLE);
		else
			findViewById(R.id.view_stockorder_detail_PageNextBut)
					.setVisibility(View.VISIBLE);
	}

	/**Procedure is to prompt confirmation to cancel, password entry, sending
	   if done, show report **/
	private void CancelOrderAction(Trade_StockHistItem focusItem)
	{
		String tmpString;
		AppDialogOKCancel cancelOrderDialog;

		editDataInProgress = true;
		cancelOrderDialog = new AppDialogOKCancel(this);

		if (systemLang.equals("lang_cht"))
			tmpString = focusItem.stockCode + "\n" + focusItem.chnName;
		else
			tmpString = focusItem.stockCode + "\n" + focusItem.engName;
		tmpString += "\n\n"
				+ getResources().getString(R.string.stockDetailOrderNoText)
				+ ": "
				+ focusItem.orderNo
				+ "\n\n"
				+ getResources().getString(
						R.string.stockDetailConfirmToCancelText);

		cancelOrderDialog.SetTextContent(tmpString);

		cancelOrderDialog.show(new AppDialogOKCancel.IAppDialogOKCancel()
		{
			@Override
			public void OnDialogCancel(DialogInterface iDialog)
			{ 
				editDataInProgress = false;
			}

			@Override
			public void OnCancel_Click(DialogInterface iDialog)
			{ 
				editDataInProgress  = false;
			}

			@Override
			public void OnOK_Click(DialogInterface iDialog)
			{
				editDataInProgress = false;
				if (TradeAppInfo.IsDemoAccount() == false)
				{
					if (IsNetworkAvailable() == false)
					{
						ShowPromptMessage(getString(R.string.commErrorText));					
						return;					
					}
				}
				
				// Open the dialog for password after the OK for modifying
				AppDialogPassword.IAppDialogPassword afterClick;

				afterClick = new AppDialogPassword.IAppDialogPassword()
				{
					@Override
					public void OnCancel_Click(DialogInterface iDialog)
					{	}

					@Override
					public void OnDialogCancel(DialogInterface iDialog)
					{	}

					@Override
					public void OnOK_Click(DialogInterface iDialog)
					{
						AppDialogPassword dialogBox;

						dialogBox = (AppDialogPassword) iDialog;

						if (isTradeOrderCancelStart == true)
							return;
						RemoveOrderProcess(
								dialogBox.GetPasswordContent(),
								transInfoList.get(focusIndex));
					}
				};
				EnterPasswordAction(afterClick);
			}
		}, true);
	}

	/** Show the EnterPassword Dialog **/
	private void EnterPasswordAction(AppDialogPassword.IAppDialogPassword iResponse)
	{
		AppDialogPassword passwordEnterDialog;

		passwordEnterDialog = new AppDialogPassword(this);
		passwordEnterDialog
				.SetTextContent(getString(R.string.stockDetailEnterPasswordText));
		passwordEnterDialog.SetPasswordContent("");
		passwordEnterDialog.show(iResponse, true, true);
	}

	private AppDialogOK promptMessage = null;
	private void ShowPromptMessage(String iContent)
	{
		if (promptMessage != null)
			promptMessage.dismiss();
		
		DismissWaitingDialog();
		promptMessage = ShowInfoBox(iContent);
	}
	
	private boolean isTradeOrderCancelStart = false;
	/** Remove the order to be sent **/
	private void RemoveOrderProcess(String iPassword,
			Trade_StockHistItem iTransItem)
	{
		if (TradeAppInfo.IsDemoAccount() == false)
		{
			if (IsNetworkAvailable() == false)
			{
				ShowPromptMessage(getString(R.string.commErrorText));
				return;
			}
		}

		// Send the actual command to cancel order
		ShowWaitingDialog();

		isTradeOrderCancelStart = true;		
		final TradeOrderCancel cancelRequest = new TradeOrderCancel(this,
				TradeAppInfo.GetUserName(), iPassword);

		cancelRequest.SetCancelOrder(iTransItem.orderNo,
				iTransItem.stockCode, iTransItem.orderSide,
				iTransItem.orderType, iTransItem.price,
				iTransItem.outstandQuantity);
		cancelRequest.SendRequest(TradeAppInfo.IsDemoAccount(),
				new ITradeOrderCancelResponse()
				{
					@Override
					public void ResponseFunc(boolean iSuccessfulSend,
							TradeOrderCancelResult iResponse)
					{
						isTradeOrderCancelStart = false;
						if (iSuccessfulSend == false)
						{
							DismissWaitingDialog();
							ShowPromptMessage(getString(R.string.commErrorText));
							return;
						}
						TradeAppInfo.ClearStockHistoryRecord();
						HandleCancelDataResult(iResponse);
						cancelRequest.Dispose();
					}
				});
	}

	private void HandleCancelDataResult(TradeOrderCancelResult iResult)
	{
		// Prepare for message
		AppDialogOK promptDialog;

		promptDialog = null;
		if ((iResult.BrokerMessage != null)
				&& (iResult.BrokerMessage.length() != 0))
		{
			promptDialog = new AppDialogOK(this);
			promptDialog.SetTextContent(iResult.BrokerMessage);
			promptDialog.SetButtonText(R.string.okText);
			// return features are based on specification
		}

		// Change order Success
		if (iResult.StatusCode.equals("3"))
		{
			// Stupid trick to make the data base to refresh
//			TradeAppInfo.ClearStockHistoryRecord();
			DismissWaitingDialog();
			// Back to the previous window, the trading option
			// The back is to return to the order History
			if (promptDialog != null)
			{
				promptDialog.show(new AppDialogOK.IAppDialogOK()
				{
					@Override
					public void OnDialogCancel(DialogInterface iDialog)
					{
						CallBackToStockOrder();
					}

					@Override
					public void OnOK_Click(DialogInterface iDialog)
					{
						CallBackToStockOrder();
					}

				}, true);
			}
			else
				CallBackToStockOrder();
			return;
		}

		// Login Session expired and kick user out to the login page
		if (iResult.StatusCode.equals("12"))
		{
			// Login Expire, Kick user out to login again
			DismissWaitingDialog();
			if (promptDialog != null)
			{
				promptDialog.show(new AppDialogOK.IAppDialogOK()
				{
					@Override
					public void OnDialogCancel(DialogInterface iDialog)
					{
						SetToLoginActivity();
					}

					@Override
					public void OnOK_Click(DialogInterface iDialog)
					{
						SetToLoginActivity();
					}
				}, true);
				return;
			}
			
			SetToLoginActivity();
			return;
		}

		DismissWaitingDialog();
		// Prompt Error if there are one and do not know what to do
		if (promptDialog != null)
			promptDialog.show(null, true);
	}

	private void EditOrderAction(Trade_StockHistItem focusItem)
	{
		String tmpString;
		AppDialogOKCancel editOrderDialog;

		editDataInProgress = true;
		
		editOrderDialog = new AppDialogOKCancel(this);

		if (systemLang.equals("lang_cht"))
			tmpString = focusItem.stockCode + "\n" + focusItem.chnName;
		else
			tmpString = focusItem.stockCode + "\n" + focusItem.engName;

		tmpString += "\n\n"
				+ getResources().getString(R.string.stockDetailOrderNoText)
				+ ": " + focusItem.orderNo
				+ "\n\n" + getResources().getString(
						R.string.stockDetailConfirmToEditText);
		editOrderDialog.SetTextContent(tmpString);

		editOrderDialog.show(new AppDialogOKCancel.IAppDialogOKCancel()
		{
			@Override
			public void OnDialogCancel(DialogInterface iDialog)
			{ 	
				editDataInProgress = false;
			}

			@Override
			public void OnCancel_Click(DialogInterface iDialog)
			{	
				editDataInProgress = false;
			}

			@Override
			public void OnOK_Click(DialogInterface iDialog)
			{
				editDataInProgress = false;				
				if (TradeAppInfo.IsDemoAccount() == false)
				{
					if (TradeAppInfo.HasSessionTimeExpired())
					{
						ShowTimeExpiredBox();
						return;
					}
					
					if (IsNetworkAvailable() == false)
					{
						ShowPromptMessage(getString(R.string.commErrorText));
						return;
					}
				}
				
				// When an OK is pressed, we will start the keypad with
				// available information
				EditOrderProcess(transInfoList.get(focusIndex));
			}
		}, true);
	}

	private final String[] reqSchema = { "StockChiShortName", "ErrorMessage", "LotSize",		
			  					  "Net", "NetPercentage", "Nominal",				
			  					  "BidPrice","AskPrice", "CurrencyCode"};
	
	private void EditOrderProcess(Trade_StockHistItem iTransItem)
	{		
		ShowWaitingDialog();

		requestCode = Trade_StockFunctionTools.FormatFullStockCode(iTransItem.stockCode);
		if (TradeAppInfo.IsDemoAccount() || TradeAppInfo.IsBMPMode())
		{
			final TradeGetDetailStockQuote quoteRequest;

			quoteRequest = new TradeGetDetailStockQuote(actContext);
			quoteRequest.SetRequestQuoteInfo(appHost.IsDevelopment(), requestCode, appHost.GetLSClient_AccountLogonName(), appHost.GetLSClient_SessionKey());
			quoteRequest.SendRequest(TradeAppInfo.IsDemoAccount(),
					new ITradeGetStockQuoteResponse()
					{
						@Override
						public void ResponseFunc(boolean iSuccessfulSend,
								TradeGetStockQuoteResult iResponse)
						{
							quoteRequest.Dispose();							
							if (iSuccessfulSend == false)
							{
								ShowPromptMessage(getString(R.string.commErrorText));
								return;
							}
	
							if (!iResponse.resultCode.equals("0"))
							{
								String textValue;
								
								textValue = iResponse.errorMessage;
								if (textValue.equals(""))
									textValue = getString(R.string.commErrorText);
								ShowPromptMessage(textValue);
								if (iResponse.resultCode.equals("-1"))
									appHost.LS_Client_ResetConnection();								
								return;
							}
							
							// The process takes too long on UI, we create
							// this to blind the user
							// DismissWaitingDialog();
							EditOrderProcessAfter(transInfoList.get(focusIndex), iResponse.stockQuoteItem);
							// Fool UI Method
							DismissWaitingDialog_Background();
						}
					});
			return;
		}
		
		//Now we are using light streamer		
		LS_SubscriptionItem quoteItem;
		
		quoteItem = new LS_SubscriptionItem("TELETEXT");
		quoteItem.AddSubscribeItem(Trade_StockFunctionTools.RemoveStockCodeFormat(requestCode));
		quoteItem.SetSubscribeSchema(reqSchema);
		
		if (lightStreamerID == null)
			lightStreamerID = LSGetUniqueID();	
		
		if (LightStreamerSubscribeItem(lightStreamerID, quoteItem, LS_ItemRequestType.NONE, this) == false)
		{		
			ShowPromptMessage(getString(R.string.SubscribeError_Text));
			return;
		}	
		
		//Hold a error message after the delay time, 8 seconds
		UIHandler.postDelayed(lightStreamerErrorPrompt, Trade_AppConstant.lightStreamerWaitTime);
		
	}		

	private String    lightStreamerID = null;
	private void LightStreamerTimeoutTaskCancel()
	{
		UIHandler.removeCallbacks(lightStreamerErrorPrompt);		
	}
	
	private Runnable lightStreamerErrorPrompt = new Runnable()
	{
		public void run()
		{
			if (lightStreamerID == null)
				return;
			
			LightStreamerUnsubscribeItem(lightStreamerID);
			
			if (debugMode)
				TDStockLog.i(GetIdentity(), "The LightStreamer(" + lightStreamerID + ")" + "requests timeout.");

			lightStreamerID = null;
			ShowPromptMessage(getString(R.string.commErrorText));	
		}
	};
	
	private String  requestCode;
	private Handler UIHandler = new Handler();
	@Override
	public void onUpdate(String iIdentifier, int iSchemaIndex,
			String iSchemaValue, UpdateInfo iUpdateInfo)
	{
		String tmpValue;
		
		tmpValue = iUpdateInfo.getNewValue("ErrorMessage");
		//Then we can prompt the error
		if ((tmpValue != null) && (tmpValue.length() > 0))
		{
			final String displayText;
			
			//Cancel our timeout task
			LightStreamerTimeoutTaskCancel();			
			if (tmpValue.equals(TradeAppInfo.stockNotFoundText))
				displayText = getString(R.string.StockNotFound_Text);
			else
				displayText = tmpValue;
			Runnable uiAcccess = new Runnable()
			{
				public void run()
				{
					ShowPromptMessage(displayText);
				}
			};					
			UIHandler.post(uiAcccess);			
			LightStreamerUnsubscribeItem(iIdentifier);
			lightStreamerID = null;			
			requestCode = null;
			return;
		}
						
		//Not check for valid date
		tmpValue = iUpdateInfo.getNewValue("StockChiShortName");
		//We consider this is a false value
		if ((tmpValue == null) || (tmpValue.length() == 0))
			return;
		
		//Cancel our timeout task
		LightStreamerTimeoutTaskCancel();
		
		String 			    tmpValue2, tmpValue3;
		Trade_StockViewInfoItem stockItem;
		
		stockItem = new Trade_StockViewInfoItem(requestCode, tmpValue, null);
		tmpValue = iUpdateInfo.getNewValue("Nominal");
		tmpValue2 = iUpdateInfo.getNewValue("BidPrice");
		tmpValue3 = iUpdateInfo.getNewValue("AskPrice");	
		stockItem.SetPriceInfo(tmpValue, tmpValue2, tmpValue3, false);
		
		tmpValue = iUpdateInfo.getNewValue("Net");
		tmpValue2 = iUpdateInfo.getNewValue("NetPercentage");
		stockItem.SetNetDiffPrice(tmpValue, tmpValue2);
		
		tmpValue = iUpdateInfo.getNewValue("LotSize");
		stockItem.SetStepVolume(tmpValue);
				
		tmpValue = iUpdateInfo.getNewValue("CurrencyCode");
		stockItem.SetCurrencyCode(tmpValue);
		
		//Calculate the spread price
		tmpValue = Trade_StockFunctionTools.GetStockPriceSpread(stockItem.GetCurPriceText());
		stockItem.SetSpreadPrice(tmpValue);
						
		LightStreamerUnsubscribeItem(iIdentifier);
		lightStreamerID = null;
		requestCode = null;		
		
		if (debugMode)
			TDStockLog.i(GetIdentity(), stockItem.toString());
		//Ready to Switch
		EditOrderProcessAfter(transInfoList.get(focusIndex), stockItem);		
		// Fool UI Method
		DismissWaitingDialog_Background();
	}

	@Override
	public void LS_UserClient_ConnectionReport(
			CONNECTION_STATUS iStatus)
	{	
		if (TradeAppInfo.IsDemoAccount() || (TradeAppInfo.IsBMPMode()))
			return;
		
		if ((iStatus != CONNECTION_STATUS.CONNECTED) && (requestCode != null))
		{
			DismissWaitingDialog();
			ShowPromptMessage(getString(R.string.SubscribeError_Text));
			if (lightStreamerID != null)
			{
				LightStreamerUnsubscribeItem(lightStreamerID);
				lightStreamerID = null;
			}			
			return;
		}
	}

	@Override
	public void ReporterTicker_Response(int iRemainSecond)
	{	}			

	/** Place the item into Bundle->Extra, not directly to the Extra
	  * Before we show that, we need to get the stock information from server
	  * Will block the UI if we can not get the data */
	private void EditOrderProcessAfter(Trade_StockHistItem iTransItem,  Trade_StockViewInfoItem iViewItem)
	{
		// When an OK is pressed, we will start the keypad with available
		// information
		Intent intentObj;
		Trade_StockReqOrderItem transferObj;

		intentObj = new Intent(actContext, Trade_ModifyKeypadActivity.class);
		if (TradeAppInfo.IsDemoAccount())
		{
			transferObj = new Trade_StockReqOrderItem("1234", iViewItem.stockCode, iViewItem.chnName,
					iViewItem.engName);
			// The outstanding is the remaining quantity for order
			transferObj.SetOrderQuantity("1200", "800", "400");
			// Use previous price for setting
			transferObj.SetOrderPrice("882.5");
			transferObj.SetOrderType("E");
			transferObj.SetOrderSide(Trade_StockReqOrderItem.TRANSACTIONTYPE_ASK);
			transferObj.SetCurrencyCode(TradeAppInfo.HKDCode);

		}
		else
		{
			transferObj = new Trade_StockReqOrderItem(iTransItem.orderNo,
					iTransItem.stockCode, iTransItem.chnName,
					iTransItem.engName);
			// The outstanding is the remaining quantity for order
			transferObj.SetOrderQuantity(iTransItem.quantity,
					iTransItem.fillQuantity, iTransItem.outstandQuantity);
			// Use previous price for setting
			transferObj.SetOrderPrice(iTransItem.price);
			transferObj.SetOrderType(iTransItem.orderType);
			transferObj.SetOrderSide(iTransItem.orderSide);
			transferObj.SetCurrencyCode(iTransItem.currencyCode);
		}
		
		intentObj.putExtra(Trade_AppConstant.stockViewInfo, iViewItem);
		intentObj.putExtra(Trade_AppConstant.stockOrderRequestInfo,
				transferObj);

		// Place the bundle object to the intent, do not kill the window
		// in case there would be a call back
		SwitchForwardActivity(Trade_ModifyKeypadActivity.class, intentObj);
	}

	private boolean editDataInProgress = false;
	@Override
	public void onClick(View iViewObj)
	{
		int objId;

		objId = iViewObj.getId();
		switch (objId)
		{
			case R.id.stockorder_details_BackBut:
				{
					Intent intentObj;
	
					intentObj = new Intent(this, Trade_AcctComboActivity.class);
					// Put something on the bundle to mark the current state
					intentObj.putExtra(Trade_AppConstant.tradingStateBundle, 0);
					SwitchFreeActivity(Trade_AcctComboActivity.class, intentObj);
				}				
				break;

			case R.id.view_stockorder_detail_EditBut:
				{
					Trade_StockHistItem focusItem;
	
					if (editDataInProgress == true)
						return;
					focusItem = transInfoList.get(focusIndex);
					EditOrderAction(focusItem);
				}
				break;

			case R.id.view_stockorder_detail_CancelBut:
				if (TradeAppInfo.HasSessionTimeExpired())
				{
					ShowTimeExpiredBox();
					return;
				}
				{
					Trade_StockHistItem focusItem;

					if (editDataInProgress == true)
						return;
					focusItem = transInfoList.get(focusIndex);
					CancelOrderAction(focusItem);
				}
				break;

			case R.id.view_stockorder_detail_PagePrevBut:
				{
					int curPage = swipFlipper.getCurrentPage();
					
					if (curPage == 0)
						break;
						
					swipFlipper.smoothScrollToPage(curPage-1);
				}
				break;
				
			case R.id.view_stockorder_detail_PageNextBut:
				{
					int curPage = swipFlipper.getCurrentPage();
					
					if ((curPage+1) >= swipFlipper.getPageCount())
						break;
						
					swipFlipper.smoothScrollToPage(curPage+1);
				}				
				break;
		}
	}

	private void CallBackToStockOrder()
	{
		Intent intentObj;

		intentObj = new Intent(this, Trade_AcctComboActivity.class);
		// Put something on the bundle to mark the current state
		intentObj.putExtra(Trade_AppConstant.tradingStateBundle, 0);
		SwitchFreeActivity(Trade_AcctComboActivity.class, intentObj);		
	}

	// *********** Swiping effect ************
	@Override
	public void onPageChanged(int oldPage, int newPage)
	{		
		int count, index;
		
		count = swipFlipper.getPageCount();
		
		//Free memory if possible
		if(newPage > oldPage)//going forwards
		{
			if(newPage != (count-1))//if at the end, don't load one page after the end
			{				
				View tmpViewObj;
				
				index = newPage+1;
				tmpViewObj = CreateContentView(transInfoList.get(index));
				((FrameLayout) swipFlipper.getChildContainer().getChildAt(index)).addView(tmpViewObj);
			}
			if(oldPage!=0)//if at the beginning, don't destroy one before the beginning
			{
				index = oldPage-1;
				((FrameLayout) swipFlipper.getChildContainer().getChildAt(index)).removeAllViews();				
			}
			
		}
		else //going backwards
		{
			if(newPage!=0)//if at the beginning, don't load one before the beginning
			{				
				View tmpViewObj;
				
				index = newPage-1;
				tmpViewObj = CreateContentView(transInfoList.get(index));				
				((FrameLayout) swipFlipper.getChildContainer().getChildAt(index)).addView(tmpViewObj);			
			}
			if(oldPage != (count-1))//if at the end, don't destroy one page after the end
			{
				index = oldPage+1;
				((FrameLayout) swipFlipper.getChildContainer().getChildAt(index)).removeAllViews();				
			}
		}		
		
		String statusCode;
		
		View       curViewObj;
		ScrollView scrollPanel;		
		curViewObj = swipFlipper.getChildContainer().getChildAt(newPage);

		statusCode = transInfoList.get(newPage).statusCode;
		UpdatePageInfo(newPage, Trade_SymbolTranslation.IsStockOrderEditable(statusCode));		
		//Page view at top
		scrollPanel = (ScrollView)curViewObj.findViewById(R.id.view_stockorder_detail_scrollPanel);
		if (scrollPanel != null)
			scrollPanel.scrollTo(0, 0);	
		
		focusIndex = newPage;
		
	}	

}
